package com.lecture.springlecture.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.api.R;
import com.lecture.java8.excel.model.DemoData;
import com.lecture.springlecture.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author luyn
 * @description
 * @Date 2020/10/23 9:52
 * @Version 1.0
 */
@RestController
public class FileController {

    @Autowired
    private UserService userService;

    @GetMapping("download")
    public void download(HttpServletRequest request, HttpServletResponse res) throws Exception {
        File excelFile = new File("G:\\VMware\\ISO\\CentOS-7-x86_64-DVD-1810.iso");
        res.setCharacterEncoding("UTF-8");
        String realFileName = excelFile.getName();
        res.setHeader("content-type", "application/octet-stream;charset=UTF-8");
        res.setContentType("application/octet-stream;charset=UTF-8");
        //加上设置大小下载下来的.xlsx文件打开时才不会报“Excel 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃”
        res.addHeader("Content-Length", String.valueOf(excelFile.length()));
        try {
            res.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(realFileName.trim(), "UTF-8"));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        byte[] buff = new byte[1024 * 1024 * 100];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(excelFile));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }   
    /**
     * 通过ResponseEntity下载文件
     * @author luyn
     * @date 2020/10/27 9:20
     * @return org.springframework.http.ResponseEntity<java.lang.Object>
     */
    @GetMapping("/downloadTest")
    @ResponseBody
    public ResponseEntity<Object> downloadFile() throws FileNotFoundException {

        File file = new File ("F:\\Microservices\\zip\\火云客户端v17.6.zip");
        InputStreamResource resource = new InputStreamResource ( new FileInputStream ( file ) );

        HttpHeaders headers = new HttpHeaders();
        headers.add ( "Content-Disposition",String.format("attachment;filename=\"%s",file.getName()));
        headers.add ( "Cache-Control","no-cache,no-store,must-revalidate" );
        headers.add ( "Pragma","no-cache" );
        headers.add ( "Expires","0" );

        ResponseEntity<Object> body = ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/txt"))
                .body(resource);
        try {
            file.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("输出华");
        return body;
    }

    /*public static void main(String[] args) {
        char c1 = 'a';
        int i1 = c1;
        System.out.println(c1);
        System.out.println(i1);
        char c2 = 10;
        int i2 = 12;
        System.out.println(c2 + i2);

        char c3 = (int)9.88;
        System.out.println(c3);
        HashMap<String, String> map = new HashMap<>();
        map.put("a","");
    }*/


    @GetMapping("async")
    public String async() {
        boolean b = userService.getAsync();
        return b ? "成功" : "失败";
    }

    @Async
    public Boolean getAsync() {
        try {
            System.out.println("开始执行。。。。。");
            Thread.sleep(5000L);
            System.out.println("执行完毕。。。。。");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("执行");
        return true;
    }

    public Boolean getThread() {
        new Thread(() -> {
            System.out.println("开始执行。。。。");
            try {
                Thread.sleep(5000L);
            } catch (Exception e) {

            }
            System.out.println("执行完毕。。。。。");
        }).start();
        System.out.println("返回结果、、、、");
        return true;
    }

    @GetMapping("thread")
    public String thread() {
        new Thread(() -> {
            System.out.println("开始执行。。。。");
            try {
                Thread.sleep(5000L);
            } catch (Exception e) {

            }
            System.out.println("执行完毕。。。。。");
        }).start();
        System.out.println("返回结果、、、、");
        return "1";
    }

    @GetMapping("downloadExcel")
    public void downloadExcel(HttpServletResponse response) throws Exception {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        List<DemoData> list = new ArrayList<>();
        DemoData demoData = new DemoData();
        demoData.setId(1L);
        demoData.setString("a");
        demoData.setDate(new Date());
        demoData.setStr("se2343t");
        demoData.setDoubleData(132.7);

        DemoData demoData1 = new DemoData();
        demoData1.setId(1L);
        demoData1.setString("a");
        demoData1.setDate(new Date());
        demoData1.setStr("s34et");
        demoData1.setDoubleData(12.237);

        DemoData demoData2 = new DemoData();
        demoData2.setId(1L);
        demoData2.setString("a");
        demoData2.setDate(new Date());
        demoData2.setStr("set34");
        demoData2.setDoubleData(12223.7);

        list.add(demoData);
        list.add(demoData1);
        list.add(demoData2);
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(),DemoData.class).build();
        WriteSheet w1 = EasyExcel.writerSheet("模板1").head(DemoData.class).build();
        WriteSheet w2 = EasyExcel.writerSheet("模板2").head(DemoData.class).build();
        excelWriter.write(list,w1);
        excelWriter.write(list,w2);
        excelWriter.finish();
    }
    @RequestMapping("/uploadFile")
    public R uploadFile(@RequestParam("files") MultipartFile[] files){
        JSONObject object=new JSONObject();
        for(int i=0;i<files.length;i++){
            String fileName = files[i].getOriginalFilename();  // 文件名
            File dest = new File("home/"+ fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                files[i].transferTo(dest);
            } catch (Exception e) {
                R.failed("上传失败");
            }
        }
        return R.ok("上传成功");
    }
}
